package com.googlecode.gwtbb.server.service;

import com.googlecode.gwtbb.client.shared.entity.forum.Forum;
import com.googlecode.gwtbb.client.shared.entity.forum.Post;
import com.googlecode.gwtbb.client.shared.remote.forum.CreatePostBean;
import com.googlecode.gwtbb.client.shared.remote.forum.CreatePostResponse;
import com.googlecode.gwtbb.client.shared.validation.Failure;
import com.googlecode.gwtbb.client.shared.validation.FieldId;
import com.googlecode.gwtbb.server.intermediate.ProcessNames;
import com.googlecode.gwtbb.server.intermediate.forum.ForumAssembler;
import com.googlecode.gwtbb.server.intermediate.forum.PostAssembler;
import com.googlecode.gwtbb.server.intermediate.forum.PostVip;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;

/**
 * @author Abraham Grief
 * @version $Id$
 * @noinspection unchecked
 * @since May 4, 2008
 */
public class PostService extends ClientService implements com.googlecode.gwtbb.client.only.remote.forum.PostService {
	private ForumAssembler forumAssembler;
	private PostAssembler postAssembler;
	private PostVip postVip;

	public ForumAssembler getForumAssembler() {
		return forumAssembler;
	}

	public void setForumAssembler(ForumAssembler forumAssembler) {
		this.forumAssembler = forumAssembler;
	}

	public PostAssembler getPostAssembler() {
		return postAssembler;
	}

	public void setPostAssembler(PostAssembler postAssembler) {
		this.postAssembler = postAssembler;
	}

	public PostVip getPostVip() {
		return postVip;
	}

	public void setPostVip(PostVip postVip) {
		this.postVip = postVip;
	}

	@Transactional
	public CreatePostResponse create(Long userId, String sessionId, CreatePostBean createPostBean) {
		if (userId == null || sessionId == null || createPostBean == null)
			return null;
		Post post = null;
		Forum forum = null;
		CreatePostResponse retVal = new CreatePostResponse();
		HashMap<FieldId, Failure> failures = newFailuresMap();
		PostVip.CreateState state = postVip.validate(failures, userId, sessionId, createPostBean);
		if (postVip.instantiatePersist(state, new Date(), ProcessNames.CREATE_POST)) {
			failures = null;
			post = postAssembler.assemble(state.getPost());
			forum = forumAssembler.assemble(state.getForum());
		}
		retVal.setFailures(failures);
		retVal.setPost(post);
		retVal.setForum(forum);
		return retVal;
	}
}